package com.neu.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageHelper;
import com.neu.constant.RoleEnum;
import com.neu.mapper.UserMapper;
import com.neu.pojo.User;
import com.neu.service.UserService;
import com.neu.utils.UserUtils;
import com.neu.vo.UserInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Override
    public List<User> queryUserListByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.queryUserList();
        return userList;
    }

    @Override
    public Object login(User user) {
        User u = userMapper.queryUserByAccount(user.getAccount());
        if (Objects.isNull(u) || !u.getPassword().equals(user.getPassword())) {
            return null;
        }
        StpUtil.login(u.getAccount());
        return StpUtil.getTokenInfo();
    }

    @Override
    public User queryUserInfoByAccount(String account) {
        return userMapper.queryUserByAccount(account);
    }

    @Override
    public Object info() {
        User user = userMapper.queryUserByAccount((String)StpUtil.getLoginId());
        List<String> roles = new ArrayList<String>();
        roles.add(RoleEnum.of(user.getRole()).des);
        return UserInfo.builder().name(user.getName()).roles(roles).build();
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }

    @Override
    public Object list() {
        return userMapper.queryUserList();
    }

    @Override
    public Object add(User user) {
//        String salt = UserUtils.generateSalt();
//        String password = UserUtils.encryptPassword("SHA-256",user.getPassword(),salt);
//        user.setSalt(salt);
//        user.setPassword(password);
        return userMapper.insertUser(user);
    }

    @Override
    public Object update(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public Object delete(int id) {
        return userMapper.deleteUser(id);
    }
}
